<?php

class ImageController extends BackEndController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'delete', 'ajaxupdate', 'multipleupload', 'adminupload', 'update'),
                'roles' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionAjaxUpdate() {
        $act = $_GET['act'];
        $autoIdAll = $_POST['autoId'];
        if (count($autoIdAll) > 0) {
            foreach ($autoIdAll as $autoId) {
                $model = $this->loadImage($autoId);
                if ($act == 'doDelete') {
                    $model->delete();
                } else {
                    if ($act == 'doActive')
                        $model->status = Image::IMAGE_ACTIVE;
                    if ($act == 'doInactive')
                        $model->status = Image::IMAGE_LOCKED;
                    if ($model->save())
                        echo 'ok';
                    else
                        throw new Exception("Sorry", 500);
                }
            }
        }
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadImage($id),
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadImage($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionIndex() {
        $model = new Image('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Image']))
            $model->attributes = $_GET['Image'];

        $this->render('index', array(
            'model' => $model,
        ));
    }

    public function actionAdminUpload() {
        $model = new Image();
        Yii::app()->session->remove("user_id");
        if (isset($_POST ['Image'])) {
            $model->attributes = $_POST ['Image'];
            Yii::app()->session->add("user_id", $model->user_created);
            $this->render('multipleupload', array('model' => $model));
        } else {
            $this->render('selectuser', array('model' => $model));
        }
    }

    public function actionUpdate($id) {
        $model = $this->loadImage($id);
        if (isset($_POST['Image'])) {
            if ($model->status==Image::IMAGE_PENDING) {
                $model->created_at = date("Y-m-d H:i:s");
            }
            $model->attributes = $_POST['Image'];      
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->id));
            }
        }
        $this->render('edit', array('model' => $model));
    }

    public function actionMultipleUpload() {
        header('Vary: Accept');
        if (isset($_SERVER['HTTP_ACCEPT']) &&
                (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
            header('Content-type: application/json');
        } else {
            header('Content-type: text/plain');
        }
        $data = array();

        $model = new Image();
        $user_id = Yii::app()->session->get("user_id");
        $uploadedFile = CUploadedFile::getInstance($model, 'img_url');
        if ($uploadedFile !== null && $model->validate(array('img_url'))) {
            $filename = md5(date("Y-m-d H:i:s") . $user_id . $uploadedFile) . '.' . $uploadedFile->extensionName;
            // save picture name
            $model->user_created = $user_id;
            $model->img_url = $filename;
            $model->status = Image::IMAGE_PENDING;
            if ($model->save()) {
                $uploadedFile->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user/' . $user_id . '/images/' . $filename);
                $image = Yii::app()->image->load(Yii::getPathOfAlias('webroot') . '/upload/user/' . $user_id . '/images/' . $filename);
                $image->quality(40);
                $image->save(Yii::getPathOfAlias('webroot') . '/upload/user/' . $user_id . '/images/small-' . $filename);
                // return data to the fileuploader
                $data[] = array(
                    'name' => $model->img_url,
                    'type' => $uploadedFile->type,
                    'size' => $uploadedFile->size,
                    // we need to return the place where our image has been saved
                    'url' => Yii::app()->baseUrl . '/upload/user/' . $user_id . '/images/' . $model->img_url, // Should we add a helper method?
                    // we need to provide a thumbnail url to display on the list
                    // after upload. Again, the helper method now getting thumbnail.
                    'thumbnail_url' => Yii::app()->baseUrl . '/upload/user/' . $user_id . '/images/' . $model->img_url,
                        // we need to include the action that is going to delete the picture
                        // if we want to after loading 
//                    'delete_url' => $this->createUrl('my/delete', array('id' => $model->id, 'method' => 'uploader')),
//                    'delete_type' => 'POST')
                );
            } else {
                $data[] = array('error' => 'Unable to save model after saving picture');
            }
        } else {
            if ($model->hasErrors('img_url')) {
                $data[] = array('error', $model->getErrors('img_url'));
            } else {
                throw new CHttpException(500, "Could not upload file " . CHtml::errorSummary($model));
            }
        }
        // JQuery File Upload expects JSON data
        echo json_encode($data);
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadImage($id) {
        $model = Image::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'image-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
